/* 
@author maodou 
@createTimer 2024/1/17
@desc  路由解析文件
*/
import { useRoutes, RouteObject, Navigate, useLocation, useNavigate } from 'react-router-dom'
interface RouterProps {
    routes: RouteObject[],
    onRouterBefore?: Function
}

let RouterView = ({ routes, onRouterBefore }: RouterProps) => {
    let element = useRoutes(routes);
    let { pathname } = useLocation();
    let navigate = useNavigate();
    //守卫
    if (onRouterBefore) {
        let path: any = onRouterBefore({ pathname });
        //检测promise
        let check = (Object.prototype.toString.call(path).match(/\s(\w+)\]/) as string[])[1]
        if (check === "Promise") {
            path.then((res: any) => {
                if (res) {
                    navigate(res);
                }
            })
        }
        else if (path && path !== pathname) {
            return <Navigate to={path}></Navigate>
        }
    }
    return element;
}
export default RouterView;